import 'package:flutter/material.dart';

class Toast {
  static void show(String message, BuildContext context) {
    final overlay = Overlay.of(context);
    late OverlayEntry overlayEntry;

    overlayEntry = OverlayEntry(
      builder: (context) => ToastWidget(
        message: message,
        onDismiss: () {
          if (overlayEntry.mounted) {
            overlayEntry.remove();
          }
        },
      ),
    );

    overlay.insert(overlayEntry);

    // 3秒后自动消失
    Future.delayed(const Duration(seconds: 3), () {
      // 双重检查确保 entry 仍然挂载
      if (overlayEntry.mounted) {
        overlayEntry.remove();
      }
    });
  }
}

class ToastWidget extends StatefulWidget {
  final String message;
  final VoidCallback onDismiss;

  const ToastWidget({
    super.key,
    required this.message,
    required this.onDismiss,
  });

  @override
  State<ToastWidget> createState() => _ToastWidgetState();
}

class _ToastWidgetState extends State<ToastWidget> {
  @override
  void initState() {
    super.initState();
    // 使用独立的定时器处理自动消失
    Future.delayed(const Duration(seconds: 3), () {
      if (mounted) {
        widget.onDismiss();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // 使用 MediaQuery.of(context).viewInsets.bottom 获取键盘高度
    final bottomInset = MediaQuery.of(context).viewInsets.bottom;

    return Positioned(
      // 键盘弹出时调整位置，确保 Toast 始终可见
      bottom: 50 + bottomInset,
      left: 20,
      right: 20,
      child: Material(
        color: Colors.transparent,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
          decoration: BoxDecoration(
            color: Colors.black45,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Text(
            widget.message,
            style: const TextStyle(color: Colors.white, fontSize: 16),
            textAlign: TextAlign.center,
          ),
        ),
      ),
    );
  }
}
